import 'dart:async';
import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_common_config.dart';
import 'package:flutter_learn_vi/src/bean/bean_user.dart';
import 'package:flutter_learn_vi/src/common/user_helper.dart';
import 'package:flutter_learn_vi/src/page/home/kuang_eails_page.dart';
import 'package:flutter_learn_vi/src/page/mine/new/score/mine_my_score_recoder_page.dart';
import 'package:flutter_learn_vi/src/page/mine/new/v2_mine_sliver_header_widget.dart';
import 'package:flutter_learn_vi/src/page/mine/new/wangpo/integral_stat_tab_page.dart';
import 'package:flutter_learn_vi/src/utils/log_util.dart';
import 'package:flutter_learn_vi/src/utils/navigator_utils.dart';

import '../../../bean/bean_app_setting.dart';
import '../../../bean/bean_mine.dart';
import '../../study/train_exam_appro_list_page.dart';
import '../../train/director_work_main_page.dart';
import '../../train/teacher_work_main_page.dart';
import '../account/order_manger_list_page.dart';
import '../mine_face_back_page.dart';
import '../mine_item2_page.dart';
import '../mine_item3_page.dart';
import '../mine_item4_page.dart';
import '../mine_item_page.dart';
import '../mine_study_recoder_page.dart';
import 'mine_collect_page.dart';
import 'mine_recoder_page.dart';
import 'score/mine_my_score_page.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2020/12/4.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单

class MineMainPersonV2Page extends StatefulWidget {
  @override
  _MinePersonPageState createState() => _MinePersonPageState();
}

///[State]生命周期封装组件
class _MinePersonPageState extends State<MineMainPersonV2Page>
    with TickerProviderStateMixin {
  //初始化要加载到图片上的高度
  double _extraPicHeight = 0;

  //图片填充类型（刚开始滑动时是以宽度填充，拉开之后以高度填充）
  BoxFit _fitType = BoxFit.fitWidth;

  //前一次手指所在处的y值
  double _prePointDy = 0;

  //动画控制器
  AnimationController _ationController;

  //Stream 控制器用来这里的局部刷新功能
  StreamController<double> _heightStreamController = new StreamController();

  //logo 使用的数据流更新
  StreamController<double> _logoStreamController = new StreamController();

  //ScrollView使用的滑动控制器
  ScrollController _scrollController = new ScrollController();

  //页面初始化方法
  @override
  void initState() {
    super.initState();
    //初始化 回弹执行时间为 400毫秒
    _ationController = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 400),
    );

    //添加一个动画执行过程实时监听
    _ationController.addListener(() {
      //_ationController.value 的值是从 0.0~1.0
      _heightStreamController
          .add(_extraPicHeight * (1.0 - _ationController.value));
    });

    //添加一个动画执行状态监听
    _ationController.addStatusListener((status) {
      //获取动画状态
      AnimationStatus animationStatus = _ationController.status;
      //动画执行完成
      if (animationStatus == AnimationStatus.completed) {
        //更新图片展开添加的高度为0
        _extraPicHeight = 0;
        //修改图片的填充方式
        _fitType = BoxFit.fitWidth;
      }
    });

    ///创建控制器
    _tabController = new TabController(
        //初始化显示的页面
        initialIndex: 0,
        //页面个数
        length: bodyWidgetList.length,
        vsync: this);
  }

  //页面销毁回调生命周期
  @override
  void dispose() {
    //关闭通道
    _heightStreamController.close();
    //释放动画控制器
    _ationController.dispose();
    super.dispose();
  }

  ///代码清单 5-29 下拉放大顶部图片Demo build函数
  ///lib/code/code5/example_507_NestScrollView.dart
  @override
  Widget build(BuildContext context) {
    //手势监听
    return Listener(
      child: Scaffold(
        body: NestedScrollView(
          physics: BouncingScrollPhysics(),
          controller: _scrollController,
          //配置可折叠的头布局
          headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
            return [
              MineSliverHeaderV2Widget(
                logoStreamController: _logoStreamController,
                streamController: _heightStreamController,
                fitType: _fitType,
                tabController: _tabController,
              ),
            ];
          },
          //页面的主体内容
          body: ListView(
            padding: EdgeInsets.only(top: 10),
            children: buildListFunction(),
          ),
        ),
      ),
      onPointerMove: (result) {
        //手指的移动时
        updatePicHeight(result.position.dy); //自定义方法，图片的放大由它完成。
      },
      onPointerUp: (result) {
        //当手指抬起离开屏幕时
        resetSetPicHeight();
      },
    );
  }

  ///子页面
  List<Widget> bodyWidgetList = [
    MineItem2Page(),
    MineItem4Page(),
    MineItem3Page(),
    MineItemPage(0),
  ];

  //创建控制器
  TabController _tabController;

  //旋转角度
  double _roateRadian = pi / 2;

  ///代码清单 5-32
  ///lib/code/code5/example_507_NestScrollView.dart
  updatePicHeight(changed) {
    //当前ScrollView滑动距离
    double offset = _scrollController.offset;
    //开始旋转的距离
    double roateOffset = 110 / 2;
    if (offset >= roateOffset && offset <= 110) {
      //计算旋转的角度
      _roateRadian = pi / 2 - (offset - roateOffset) / (roateOffset) * pi / 2;
      _logoStreamController.add(_roateRadian);
      LogUtils.e("滑动距离 offset $offset  roateFlag $_roateRadian");
    } else if (offset >= 110) {
      if (_roateRadian != 0.0) {
        _roateRadian = 0.0;
        _logoStreamController.add(0.0);
      }
    } else {
      if (_roateRadian != pi / 2) {
        _roateRadian = pi / 2;
        _logoStreamController.add(pi / 2);
      }
    }
    print(
        "_defaultExpandHeight 110  extraPicHeight $_extraPicHeight prev_dy $_prePointDy");
    //安全判断  qwer 77890
    if (_prePointDy == 0.0) {
      _prePointDy = changed;
    }
    //向下滑动时 会大于0
    if (_extraPicHeight >= 0) {
      //改变图片的填充方式，让它由以宽度填充变为以高度填充，从而实现了图片视角上的放大。
      _fitType = BoxFit.fill;
    } else {
      //向上滑动时折叠隐藏
      _fitType = BoxFit.fitWidth;
    }
    //每次滑动的距离 加载到图片上的高度。
    _extraPicHeight += (changed - _prePointDy) / 10;
    //更新手指位点坐标
    _prePointDy = changed;
    //只有向下滑动时图片放大的情况再更新放大的效果
    if (_extraPicHeight >= 0) {
      //更新图片的高度
      _heightStreamController.add(_extraPicHeight);
    } else {
      //如果是向上折叠的过程不记录手指点位
      _prePointDy = 0.0;
    }
  }

  ///代码清单 5-33
  ///lib/code/code5/example_507_NestScrollView.dart
  resetSetPicHeight() {
    if (_prePointDy >= 0) {
      _prePointDy = 0;
      //设置动画让extraPicHeight的值从当前的值渐渐回到 0
      _ationController.reset();
      _ationController.forward();
    }
  }

  buildListFunction() {
    bool show02 = false;
    AppSettingBean appSettingBean = UserHelper.getInstance.appSettingBean;
    UserBean userBean = UserHelper.getInstance.userBean;
    if (userBean != null) {
      //iOS审核中
      show02 = userBean.isIosCheck == 1;
    }

    List<CommonConfigBean> configList = UserHelper.getInstance.configList;

    //UserBean userBean = UserHelper.getInstance.userBean;
    MineBean mine = UserHelper.getInstance.mineBean;

    List<Widget> list = [];

    if (!show02) {
      list.add(buildManagerCenter());
      list.add(SizedBox(
        height: 16,
      ));
    }
    int isDirector = userBean.isDirector;
    int isTeacher = userBean.isTeacher;
    // 班主任  0 APP内容全部显示  1  只显示工作台
    int showDirectorWorkBench = userBean.showDirectorWorkBench;
    // 教师  0 APP内容全部显示  1  只显示工作台
    int showTeacherWorkBench = userBean.showTeacherWorkBench;

    if (isDirector == 1 || isTeacher == 1) {
      list.add(buildTrainDirectorCenter());
      list.add(SizedBox(
        height: 16,
      ));
    }
    if (showDirectorWorkBench != 1 && showTeacherWorkBench != 1) {
      list.add(
        buildItem("我的收藏", "assets/images/2.0x/collecg_icon", MyCollectPage()),
      );

      ///成绩考核统计 cl 关闭 op 开启
      String scoreStatistics = mine.scoreStatistics;
      String integralExchange = mine.integralExchange;
      if (integralExchange == "op") {
        if (!show02) {
          list.add(
            buildItem(
              "积分排行榜",
              "assets/images/2.0x/jifeng_icon",
              IntegralAllMineStatTabPage(),
            ),
          );
          list.add(
            buildItem(
              "我的积分记录",
              "assets/images/2.0x/paihang_icon",
              MyScorePage(
                scoreRankType: ScoreRankType.integralStatisticsRecoder,
              ),
            ),
          );
          // list.add(
          //   buildItem(
          //     "专项积分",
          //     "assets/images/3.0x/zhuanxiang",
          //     SpecialMainPage(),
          //   ),
          // );
        }
      } else {
        if (configList != null) {
          configList.forEach((CommonConfigBean element) {
            if (element.configType == 2) {
              if (element.open == 0) {
                list.add(
                  buildItem(
                      "学习排行榜",
                      "assets/images/2.0x/paihang_icon",
                      MyScorePage(
                        scoreRankType: ScoreRankType.rank,
                      )),
                );
              }
            } else if (element.configType == 1) {
              if (element.open == 0) {
                list.add(
                  buildItem(
                    "积分排行榜",
                    "assets/images/2.0x/jifeng_icon",
                    MyScorePage(
                      scoreRankType: ScoreRankType.integral,
                    ),
                  ),
                );
              }
            }
          });
        }
        if (!show02) {
          list.add(
            buildItem(
                "我的积分记录",
                "assets/images/2.0x/score_icon",
                MyScorePage(
                  scoreRankType: ScoreRankType.score,
                )),
          );
        }
      }

      list.add(
        buildItem("我的答题记录", "assets/images/2.0x/srecoder_icon",
            MineMyScoreRecoderPage()),
      );
      list.add(buildItem(
          "我的足迹", "assets/images/2.0x/recoder_icon", MyRecoderPage()));

      list.add(buildItem(
          "我的学习", "assets/images/2.0x/sstudy_icon", MyStudyRecoderPage()));

      list.add(SizedBox(
        height: 16,
      ));
      if (userBean.userType == 1) {
        list.add(buildItem(
            "领导信箱", "assets/images/2.0x/xinxiang_icon", EamilsListPage()));
      } else {
        list.add(buildItem(
            "领导信箱", "assets/images/2.0x/xinxiang_icon", FaceBackPage(1)));
        list.add(buildItem(
            "职工建议", "assets/images/2.0x/xinxiang_icon", FaceBackPage(2)));
      }

      if (scoreStatistics == "op") {
        // list.add(buildItem(
        //     "我的考核", "assets/images/3.0x/examine_doing", ExaminListPage()));
      }
      // if (integralExchange == "op") {
      //   if (!show02) {
      //     //积分兑换
      //     list.add(buildItem(
      //         "积分兑换",
      //         "assets/images/3.0x/shngcheng",
      //         AccountCenterPage(
      //           tag: "mine",
      //         )));
      //   }
      // }
    }

    //MineMainBlocAddresPage
    //MyAddressListPage
    // if (UserHelper.getInstance.userBean.userBlocType == 1) {
    //   list.add(buildItem("集团通讯录", "assets/images/2.0x/tongxunlu_icon",
    //       MineBlocAddressItemPage()));
    // } else {
    //   list.add(buildItem("集团通讯录", "assets/images/2.0x/tongxunlu_icon",
    //       MineSelectDepartmentPage()));
    // }

    return list;
  }

  buildTrainDirectorCenter() {
    UserBean userBean = UserHelper.getInstance.userBean;

    //对应的审批 默认为0 无审批权限 2为二级审批 1为一级审批
    int isApprove = userBean.isApprove;

    ///isDirector 是否是培训班主任 默认0不是 ；1为是
    ///isTeacher  是否是培训教师  默认0不是 ；1为是
    if (userBean.isDirector == 0 && userBean.isTeacher == 0 && isApprove == 0) {
      return SizedBox();
    }
    return Container(
        margin: EdgeInsets.only(bottom: 8, left: 12, right: 12),
        padding: EdgeInsets.only(left: 10, right: 10, top: 10),
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(4))),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              "培训管理中心",
              style: TextStyle(fontSize: 16, color: Colors.blueGrey[600]),
            ),
            buildDirectorWidget(userBean),
            buildTeacherWidget(userBean),
            buildApproveWidget(userBean),
          ],
        ));
  }

  buildApproveWidget(UserBean userBean) {
    UserBean userBean = UserHelper.getInstance.userBean;
    //对应的审批 默认为0 无审批权限 2为二级审批 1为一级审批
    int isApprove = userBean.isApprove;
    if (isApprove != 0) {
      return SizedBox();
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        SizedBox(
          height: 12,
        ),
        Text(
          "培训考核审批",
          style: TextStyle(fontSize: 14, color: Colors.grey[600]),
        ),
        SizedBox(
          height: 1,
        ),
        TextButton(
          onPressed: () {
            NavigatorUtils.pushPage(
              context,
              TrainExamApproListPage(),
            );
          },
          child: Text("点击查看我的审批"),
        ),
      ],
    );
  }

  buildDirectorWidget(UserBean userBean) {
    if (userBean.isDirector == 0) {
      return SizedBox();
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        SizedBox(
          height: 12,
        ),
        Text(
          "班主任权限，支持管理班主任的工作日志",
          style: TextStyle(fontSize: 14, color: Colors.grey[600]),
        ),
        SizedBox(
          height: 1,
        ),
        TextButton(
          onPressed: () {
            NavigatorUtils.pushPage(
              context,
              DirectorTeacherWorkMainPage(),
            );
          },
          child: Text("进入班主任工作台"),
        ),
      ],
    );
  }

  buildTeacherWidget(UserBean userBean) {
    if (userBean.isTeacher == 0) {
      return SizedBox();
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        SizedBox(
          height: 12,
        ),
        Text(
          "培训教师权限，目前支持 查看教师参与的培训以及签到",
          style: TextStyle(fontSize: 14, color: Colors.grey[600]),
        ),
        SizedBox(
          height: 1,
        ),
        TextButton(
          onPressed: () {
            NavigatorUtils.pushPage(context, TeacherWorkMainPage());
          },
          child: Text("进入教师工作台"),
        ),
      ],
    );
  }

  ///积分兑换管理中心
  buildManagerCenter() {
    UserBean userBean = UserHelper.getInstance.userBean;
    if (userBean.userManager == 0) {
      return SizedBox();
    }
    return Container(
        margin: EdgeInsets.only(bottom: 8, left: 12, right: 12),
        padding: EdgeInsets.only(left: 10, right: 10, top: 10),
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(4))),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              "管理中心",
              style: TextStyle(fontSize: 16, color: Colors.blueGrey[600]),
            ),
            SizedBox(
              height: 12,
            ),
            Text(
              "管理员权限，目前支持查看积分订单与发货的功能",
              style: TextStyle(fontSize: 14, color: Colors.grey[600]),
            ),
            SizedBox(
              height: 1,
            ),
            TextButton(
                onPressed: () {
                  NavigatorUtils.pushPage(context, OrderManagerListPage());
                },
                child: Text("查看积分订单"))
          ],
        ));
  }

  Widget buildItem(String title, String iconData, Widget page) {
    return Container(
      margin: EdgeInsets.only(top: 1.0),
      color: Colors.white,
      child: ListTile(
        title: Text(title),
        trailing: Icon(
          Icons.arrow_forward_ios,
          size: 14,
        ),
        leading: Image.asset(
          "$iconData.png",
          width: 22,
        ),
        onTap: () {
          NavigatorUtils.pushPage(context, page);
        },
      ),
    );
  }
}

class MineMenuItemBean {
  String title;
  String iconPath;
  Widget tagPage;
}
